<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class UpdateUserBalance implements ShouldQueue,ShouldBeUnique
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $user;
    public $amount;

    /**
     * 作业的唯一锁释放后的秒数。
     *
     * @var int
     */
    public $uniqueFor = 30;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(User $user,float $amount)
    {
        $this->user = $user;
        $this->amount = $amount;
    }

    // 定义唯一锁标识（基于用户ID）
    public function uniqueId(): string
    {
        return 'user_balance_' . $this->user->id;
    }

    /**
     * Execute the job.
     * 用supervisor守护进程守护队列，配置文件在根目录下的supervison
     * @return void
     */
    public function handle()
    {
        //事务更新用户余额
        DB::transaction(function () {
            // 使用悲观锁保证数据一致性
            $user = User::where('id', $this->user->id)
                ->lockForUpdate()
                ->first();

            $user->balance += $this->amount;
            $user->save();
        });
    }
}
